﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using VehicleScale.Models;
using VehicleScale.EntityMappers;
using System.Diagnostics;

namespace VehicleScale.DataAccess
{
    public class VehicleScaleDataAccess : BaseDataAccess, IVehicleScaleDataAccess
    {

        #region Property
        private VehicleScaleModel _searchObject;
        /// <summary>
        /// Search object property
        /// </summary>
        public VehicleScaleModel SearchObject
        {
            get { return _searchObject; }
            set
            {
                if (_searchObject != value)
                {
                    _searchObject = value;
                }
            }
        }

        /// <summary>
        /// ToDate Property
        /// </summary>
        public DateTime ToDate
        {
            get;
            set;
        }

        /// <summary>
        /// Vehicle ID Property
        /// </summary>
        public string VehicleID
        {
            get;
            set;
        }

        /// <summary>
        /// Details Property
        /// </summary>
        public IList<VehicleScaleDetailModel> Details
        {
            get;
            set;
        }
        #endregion

        #region Methods
        /// <summary>
        /// Search Method
        /// </summary>
        /// <returns></returns>
        public IList<VehicleScaleModel> Searcher()
        {
            IList<VehicleScaleModel> collection;
            using (DataClassesDataContext dataContext = new DataClassesDataContext(base.ConnectionString))
            {
                IQueryable<VehicleScale> query = dataContext.VehicleScales;
                if (!String.IsNullOrEmpty(_searchObject.CustomerID))
                {
                    query = query.Where(e => e.CustomerID.Contains(_searchObject.CustomerID));
                }
                // Employee logining
                if (!String.IsNullOrEmpty(_searchObject.EmployeeID))
                {
                    query = query.Where(e => e.EmployeeID == _searchObject.EmployeeID);
                }
                if (!String.IsNullOrEmpty(_searchObject.ProductID))
                {
                    query = query.Where(e => e.ProductID.Contains(_searchObject.ProductID));
                }
                if (!String.IsNullOrEmpty(_searchObject.CategoryID))
                {
                    query = query.Where(e => e.Product.CategoryID.Contains(_searchObject.CategoryID));
                }
                if (_searchObject.ImExType > 0)
                {
                    query = query.Where(e => e.ImExType == _searchObject.ImExType);
                }
                query = query.Where(e => e.ScaleDate >= _searchObject.ScaleDate && e.ScaleDate <= ToDate);
               

                collection = new List<VehicleScaleModel>();
                Details = new List<VehicleScaleDetailModel>();

                VehicleScaleModel model;
                foreach (var item in query)
                {
                    model = VehicleScaleMapper.ToModel(item, 1);
                   
                    if (item.VehicleScaleDetails != null && item.VehicleScaleDetails.Count() > 0)
                    {

                        VehicleScaleDetailModel subModel;
                        foreach (var subItem in item.VehicleScaleDetails)
                        {
                            subModel = VehicleScaleDetailMapper.ToModel(subItem);
                            Details.Add(subModel);
                        }
                        Details = Details.OrderBy(x=>x.ScaleTime2).ToList();
                    }
                   
                    collection.Add(model);
                }

            }
            return collection;
        }

        public IList<VehicleScaleDetailModel> SearchDetails(VehicleScaleModel vehicle)
        {
            IList<VehicleScaleDetailModel> collection;
            collection = new List<VehicleScaleDetailModel>();
             using (DataClassesDataContext dataContext = new DataClassesDataContext(base.ConnectionString))
            {
                 IQueryable<VehicleScaleDetail> query = dataContext.VehicleScaleDetails;
                 if (vehicle != null)
                 {
                     query = query.Where(x => x.VehicleScaleID == vehicle.VehicleScaleID);
                 }
                 
                 VehicleScaleDetailModel model;
                 foreach (var item in query)
                 {
                     model = VehicleScaleDetailMapper.ToModel(item);
                     collection.Add(model);
                 }
                 collection = collection.OrderBy(x => x.ScaleTime2).ToList();
                 return collection;
             }
        }
        /// <summary>
        /// Get Method
        /// </summary>
        /// <returns></returns>
        public VehicleScaleModel Get()
        {
            throw new NotImplementedException();
        }

        /// <summary>
        /// Get Last Method
        /// </summary>
        /// <returns></returns>
        public VehicleScaleModel GetLast()
        {
            throw new NotImplementedException();
        }

        /// <summary>
        /// Get all Method
        /// </summary>
        /// <returns></returns>
        public IList<VehicleScaleModel> GetAll()
        {
            throw new NotImplementedException();
        }

        /// <summary>
        /// Add Method
        /// </summary>
        /// <param name="item"></param>
        /// <returns></returns>
        public bool Add(VehicleScaleModel item, out string detailerror)
        {
            detailerror = String.Empty;
            bool result = false;
            try
            {
                using (DataClassesDataContext dataContext = new DataClassesDataContext(base.ConnectionString))
                {
                    if (String.IsNullOrEmpty(item.VehicleScaleID))
                    {
                        item.VehicleScaleID = GenerateAutoID(item, dataContext);
                    }

                    // item.VehicleScaleID = Guid.NewGuid();
                    VehicleScale entity = new VehicleScale();
                    VehicleScaleMapper.ToEntity(entity, item);

                    if (item.VehicleScaleDetails != null && item.VehicleScaleDetails.Count > 0)
                    {
                        entity.VehicleScaleDetails = new System.Data.Linq.EntitySet<VehicleScaleDetail>();
                        foreach (var detail in item.VehicleScaleDetails)
                        {
                            detail.VehicleScaleID = item.VehicleScaleID;
                            entity.VehicleScaleDetails.Add(VehicleScaleDetailMapper.ToEntity(new VehicleScaleDetail(), detail));
                        }
                    }

                    if (item.VehicleScaleSplits != null && item.VehicleScaleSplits.Count > 0)
                    {
                        entity.VehicleScaleSplits = new System.Data.Linq.EntitySet<VehicleScaleSplit>();
                        foreach (var detail in item.VehicleScaleSplits)
                        {
                            detail.VehicleScaleID = item.VehicleScaleID;
                            entity.VehicleScaleSplits.Add(VehicleScaleSplitMapper.ToEntity(new VehicleScaleSplit(), detail));
                        }
                    }

                    dataContext.VehicleScales.InsertOnSubmit(entity);
                    dataContext.SubmitChanges();
                    result = true;
                    item.IsNew = false;
                    item.IsEdit = false;
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex.Message);
                detailerror = ex.Message;
            }
            return result;
        }

        /// <summary>
        /// Generate Auto ID Method
        /// </summary>
        /// <param name="item"></param>
        /// <param name="dataContext"></param>
        /// <returns></returns>
        private static string GenerateAutoID(VehicleScaleModel item, DataClassesDataContext dataContext)
        {
            int thismonth = DateTime.Today.Month;
            int thisyear = DateTime.Today.Year;
            var config = dataContext.Configs.FirstOrDefault();
            string defaultID = String.Empty;
            string prefix = "NH/";
            int startIndex = 1;
            int length = 17;
            if (config != null)
            {
                int newmonth = dataContext.VehicleScales.Count(v => v.CreationDate.Month == thismonth && v.CreationDate.Year == thisyear && v.ImExType == item.ImExType);
                prefix = DateTime.Today.ToString("yyyyMMdd");
                switch (item.ImExType)
                {
                    case 1:
                        prefix += config.VehicleScaleImPrefix.PadLeft(3, ' ');
                        if (newmonth == 0)
                        {
                            startIndex = 1;
                        }
                        else
                        {
                            startIndex = config.VehicleScaleImStart + 1;
                        }
                        length = config.VehicleScaleImLength;
                        config.VehicleScaleImStart = startIndex;
                        break;
                    case 2:
                        prefix += config.VehicleScaleExPrefix.PadLeft(3, ' ');
                        if (newmonth == 0)
                        {
                            startIndex = 1;
                        }
                        else
                        {
                            startIndex = config.VehicleScaleExStart + 1;
                        }
                        length = config.VehicleScaleExLength;
                        config.VehicleScaleExStart = startIndex;
                        break;
                }
            }

            return prefix + startIndex.ToString().PadLeft(length, '0');
            // End Create Automation Key
        }

        /// <summary>
        /// Add Collection
        /// </summary>
        /// <param name="collection"></param>
        /// <returns></returns>
        public bool Add(IList<VehicleScaleModel> collection)
        {
            throw new NotImplementedException();
        }

        /// <summary>
        /// Edit Method
        /// </summary>
        /// <param name="item"></param>
        /// <returns></returns>
        public bool Edit(VehicleScaleModel item, out string detailerror)
        {
            detailerror = String.Empty;
            bool result = false;
            try
            {
                using (DataClassesDataContext dataContext = new DataClassesDataContext(base.ConnectionString))
                {
                    var entity = (from v in dataContext.VehicleScales
                                  where v.VehicleScaleID == item.VehicleScaleID
                                  select v).FirstOrDefault();
                    if (entity != null)
                    {
                        VehicleScaleMapper.ToEntity(entity, item);

                        dataContext.VehicleScaleDetails.DeleteAllOnSubmit(entity.VehicleScaleDetails);

                        if (item.VehicleScaleDetails != null && item.VehicleScaleDetails.Count > 0)
                        {
                            entity.VehicleScaleDetails = new System.Data.Linq.EntitySet<VehicleScaleDetail>();
                            foreach (var detail in item.VehicleScaleDetails)
                            {
                                detail.VehicleScaleID = item.VehicleScaleID;
                                entity.VehicleScaleDetails.Add(VehicleScaleDetailMapper.ToEntity(new VehicleScaleDetail(), detail));
                            }
                        }

                        dataContext.VehicleScaleSplits.DeleteAllOnSubmit(entity.VehicleScaleSplits);

                        if (item.VehicleScaleSplits != null && item.VehicleScaleSplits.Count > 0)
                        {
                            entity.VehicleScaleSplits = new System.Data.Linq.EntitySet<VehicleScaleSplit>();
                            foreach (var detail in item.VehicleScaleSplits)
                            {
                                detail.VehicleScaleID = item.VehicleScaleID;
                                entity.VehicleScaleSplits.Add(VehicleScaleSplitMapper.ToEntity(new VehicleScaleSplit(), detail));
                            }
                        }

                        dataContext.SubmitChanges();
                        result = true;
                        item.IsNew = false;
                        item.IsEdit = false;
                    }
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex.Message);
                detailerror = ex.Message;
            }
            return result;
        }

        /// <summary>
        /// Edit collection Method
        /// </summary>
        /// <param name="collection"></param>
        /// <returns></returns>
        public bool Edit(IList<VehicleScaleModel> collection)
        {
            throw new NotImplementedException();
        }

        /// <summary>
        /// Delete Method
        /// </summary>
        /// <param name="item"></param>
        /// <returns></returns>
        public bool Delete(VehicleScaleModel item)
        {
            bool result = false;
            try
            {
                using (DataClassesDataContext dataContext = new DataClassesDataContext(base.ConnectionString))
                {
                    var entity = (from v in dataContext.VehicleScales
                                  where v.VehicleScaleID == item.VehicleScaleID
                                  select v).FirstOrDefault();
                    if (entity != null)
                    {
                        dataContext.VehicleScaleDetails.DeleteAllOnSubmit(entity.VehicleScaleDetails);
                        dataContext.VehicleScaleSplits.DeleteAllOnSubmit(entity.VehicleScaleSplits);
                        dataContext.VehicleScales.DeleteOnSubmit(entity);
                        dataContext.SubmitChanges();

                        result = true;
                    }
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex.Message);
            }
            return result;
        }

        /// <summary>
        /// Delete Collection Method
        /// </summary>
        /// <param name="collection"></param>
        /// <returns></returns>
        public bool Delete(IList<VehicleScaleModel> collection)
        {
            throw new NotImplementedException();
        }
        #endregion

        #region IVehicleScaleDataAccess Members


        public bool Add(VehicleScaleModel model, string detailerror)
        {
            throw new NotImplementedException();
        }

        #endregion

        #region IBaseDataAccess<VehicleScaleModel> Members


        public bool Add(VehicleScaleModel item)
        {
            throw new NotImplementedException();
        }

        public bool Edit(VehicleScaleModel item)
        {
            bool result = false;
            try
            {
                using (DataClassesDataContext dataContext = new DataClassesDataContext(base.ConnectionString))
                {
                    var entity = (from v in dataContext.VehicleScales
                                  where v.VehicleScaleID == item.VehicleScaleID
                                  select v).FirstOrDefault();
                    if (entity != null)
                    {
                        VehicleScaleMapper.ToEntity(entity, item);

                        dataContext.SubmitChanges();
                        result = true;
                        item.IsNew = false;
                        item.IsEdit = false;
                    }
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex.Message);
            }
            return result;
        }

        #endregion
    }
}
